//************************************************************
//
// REGSTEP 9.  REACTION FUNCTION WITH MEDIAN FIRM
//
// AUTHOR: LIONEL NESTA
//
// DATASOURCE: USING final_reaction_functions.dta FROM DATASTEP 5
//
//*************************************************************


// PREAMBLE
*set processors 24

clear
clear matrix 
clear mata
set more off
set mem 600m
set matsize 800
pwd 
cd ..\DATA

// OPENING FILE

use final_reaction_functions.dta, clear
set more off

* Building instruments

gen case = case1

cd ..\RESULTS

// DROPS ALL RF OUTSIDE CORNERS 1 TO 4 IN BETA-SIGMA SPACE 

 drop if case == .

local listpct "mean p01 p05 p10 p25 p50 p75 p90 p95 p99" // 

mat RES = J(44,4,.)

local line = 1
foreach p of local listpct {
	
	preserve
	collapse (`p') lnrd2 lnrdi2 (mean) lnrd1  c_techno_c c_market_c lnk1 lnliq_ratio1 msh1 msh12 lnrdpatsm1 psm_* L1lnrdpatsm1 lnk2 lnliq_ratio2 msh2 msh22 lnrdpatsm2 L1lnrd1 L1lnrd2 L1lnk1 L1lnliq_ratio1 L1msh1 L2lnrdpatsm1 L2lnrdpatsm2 mrd_sec*, by(gvkey1 year case)


	drop if case == .
	drop if year < 1990
	tabulate year, gen(year_)

	egen fcid  = group(gvkey1 case)
	tsset fcid year

	forvalues  case = 1/4 {
		*quietly {
		*reg lnrd1 lnrd2 lnk1 lnliq_ratio1 lnrdpatsm1 year_*  if case == `case'
		display "percentile ""`p'"
		display "Case ""`case'"
		noisily: cap ivreg2 lnrd1 lnk1 lnliq_ratio1 L1lnrdpatsm1 psm_lnrd1 year_* (lnrd2 = L1lnrd2 mrd_sec2_fs) if case == `case' & case < 3, robust gmm2s
		noisily: cap ivreg2 lnrd1 lnk1 lnliq_ratio1 L1lnrdpatsm1 psm_lnrd1 year_* (lnrd2 = L1lnrd2 mrd_sec2) if case == `case' & case >2, robust gmm2s
		*}
		local linac = `line' 
		mat RES[`linac', `case'] = _b[lnrd2] 
		local linac = `linac' + 1
		mat V = e(V)
		local se =  V[1,1]^(1/2)
		mat RES[`linac', `case'] =  `se'
		local linac = `linac' + 1
		local beta = _b[lnrd2]
		local z = `beta' / `se'
		if `case '< 3 {
				mat RES[`linac', `case'] = 1 - normal(`z') 
			}
			else {
				mat RES[`linac', `case'] = normal(`z') 
			}
		}

	local line = `line' + 4 
	restore
	
	}


clear

svmat RES, names(case)


local listpct "mean p01 p05 p10 p25 p50 p75 p90 p95 p99" 
local line = 1
gen pct = ""
foreach p of local listpct {
	replace pct = "`p'" in `line'
	local line = `line' + 4
} 


forvalues x = 1(1)4 {
	format case`x' %12.3f
} 
	
order  pct

dataout , save(table3_pct)  dec(3) word tex excel replace
